import os
import sys
import tempfile
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, send_file
from dotenv import load_dotenv  # 新增环境变量加载

# 设置项目根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)

# 先加载环境变量
load_dotenv(os.path.join(BASE_DIR, '.env'))  # 从项目根目录加载.env文件

from model import OpenAIModel
from translator import PDFTranslator

app = Flask(__name__)
upload_folder = r'C:\Users\76219\Downloads'
# 配置参数
app.config.update({
    'UPLOAD_FOLDER': tempfile.gettempdir(),
    'MAX_CONTENT_LENGTH': 16 * 1024 * 1024,  # 16MB
    'ALLOWED_EXTENSIONS': {'pdf'},
    'OPENAI_API_KEY': os.getenv("OPENAI_API_KEY"),
    'OPENAI_MODEL': os.getenv("OPENAI_MODEL", "gpt-3.5-turbo")
})


def validate_environment():
    """环境验证函数"""
    if not app.config['OPENAI_API_KEY']:
        raise RuntimeError("OPENAI_API_KEY 未配置")
    if not app.config['OPENAI_MODEL']:
        raise RuntimeError("OPENAI_MODEL 未配置")


def allowed_file(filename):
    """文件验证函数"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/', methods=['GET', 'POST'])
def handle_translation():
    global output_path
    if request.method == 'POST':
        # 检查文件上传
        if 'pdf_file' not in request.files:
            return render_template('index.html', error="请选择PDF文件")

        pdf_file = request.files['pdf_file']

        # 验证文件有效性
        if pdf_file.filename == '':
            return render_template('index.html', error="无效的文件")
        if not allowed_file(pdf_file.filename):
            return render_template('index.html', error="仅支持PDF格式")

        temp_pdf = None
        try:
            # 保存临时文件
            filename = secure_filename(pdf_file.filename)
            # temp_pdf = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            temp_pdf = os.path.join(upload_folder, filename)
            pdf_file.save(temp_pdf)

            # 获取输出格式
            file_format = request.form.get('format', 'markdown')

            # 初始化翻译器
            model = OpenAIModel(
                model=app.config['OPENAI_MODEL'],
                api_key=app.config['OPENAI_API_KEY']
            )
            translator = PDFTranslator(model)
            print("临时文件路径" + temp_pdf)
            # 执行翻译
            pdf_file_path = None
            output_path = translator.translate_pdf(
                pdf_file_path=temp_pdf,
                file_format=file_format
            )

            # 返回结果文件
            # return send_file(
            #     output_path,
            #     as_attachment=True,
            #     download_name=f"translated_{os.path.splitext(filename)[0]}.{file_format}"
            # )

        except Exception as e:
            app.logger.error(f"翻译失败: {str(e)}", exc_info=True)
            return render_template('index.html', error=f"处理失败: {str(e)}")

        finally:
            # 清理临时文件
            if temp_pdf and os.path.exists(temp_pdf):
                os.remove(temp_pdf)
            if 'output_path' in locals() and os.path.exists(output_path):
                os.remove(output_path)

    return render_template('index.html')


if __name__ == '__main__':
    # 环境预检查
    try:
        validate_environment()
        os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
        app.run(host='0.0.0.0', port=5000, debug=True)
    except Exception as e:
        print(f"启动失败: {str(e)}")
        sys.exit(1)
